import React, { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
// 引入仓库方法
import { addimagecanvas } from '@/store/modules/modules'
// 引入抠图插件
import backgroundRemoval from '@imgly/background-removal';
// 引入对话框
import { Modal, Button, Spin } from 'antd';
function Cutout({isModalOpen2 ,setIsModalOpen2}:any) {
    const dispatch = useDispatch()
    //原图
    const [imageUrl, setImageUrl] = useState('');
    // resultUrl 扣完后的图片
    const [resultUrl, setResultUrl] = useState('');
    const handleCancel2 = () => {
        setIsModalOpen2(false);
    };
    const handleOk2 = () => {
        setIsModalOpen2(false);
    };
    //抠图
    const handleImageUpload = async (event: any) => {
        setImageUrl('')
        setResultUrl('')
        //获取上传的文件资源
        const file = event.target.files[0];
        //实例化
        const reader: any = new FileReader();
        console.log(reader, 'reader')
        reader.onloadend = async () => {
            // 给原图做赋值
            setImageUrl(reader.result);
            // 移除图像背景
            const result = await backgroundRemoval(reader.result);
            // console.log(result,'抠图结果')
            const url = URL.createObjectURL(result)
            // console.log(url, 'base64 抠图数据')
            //给抠图后的src赋值
            setResultUrl(url);
        };
        //读取base64 图片
        if (file) {
            reader.readAsDataURL(file);
        }
    };
    //把扣完的图插入画布
    const addcanvas = () => {
        //派发动作
        dispatch(addimagecanvas(resultUrl))
        //关闭弹框
        setIsModalOpen2(false);
    }
    /* drag-button */
    var cutout: any = ''
    //判断 只有在抠图的时候 出现加载组件
    if (!resultUrl && imageUrl) {
        cutout = <Spin />
    }
    return (

        <Modal title="扣图" open={isModalOpen2} onOk={handleOk2} onCancel={handleCancel2} footer={null}>
            <div style={{ position: 'relative', height: '500px' }}>
                <input type="file" accept="image/*" onChange={handleImageUpload} />
                <br />
                {imageUrl && (
                    <div style={{ float: 'left' }}>
                        <h3>原图</h3>
                        <img width={200} src={imageUrl} alt="Original" />
                    </div>
                )}
                {
                    cutout
                }
                {resultUrl && (
                    <div style={{ float: 'right' }}>
                        <h3>抠图完毕</h3>
                        <img width={200} src={resultUrl} alt="Background Removed" /><br />
                        <Button type='primary' danger onClick={addcanvas}>插入画布</Button>
                    </div>
                )}
            </div>
        </Modal>
    )
}

export default Cutout
